﻿/*
   Created 2009 December 6, Randall Maas
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/


using System;
using System . Windows. Forms; 
using System . Runtime . InteropServices;
using System . Diagnostics;
using System . Threading;

partial class DirectShowGraph : IDisposable
{
   /// <summary>
   /// Delegate used to rank the media types
   /// </summary>
   /// <param name="Type">The Media Subtype</param>
   /// <returns></returns>
   internal delegate int RankType (AMMediaType Type);


   /// <summary>
   /// A helper to find the best media format
   /// </summary>
   /// <param name="Rank"></param>
   /// <returns></returns>
   internal AMMediaType BestMediaType(RankType Rank)
   {
      int BestRank=-1;
      AMMediaType VideoMedia = null;
      if (VideoOuts . Count < 1)
        return null;

      IPin Pin = VideoOuts[VideoOuts . Count-1];
      foreach (AMMediaType MT in DirectShowNode . EnumerateMedia(Pin))
      {
         int Ranking = Rank(MT);
         // See if it is better
         if (Ranking < BestRank)
           continue;
         BestRank  = Ranking;
         VideoMedia = MT;
      }
      return VideoMedia;
   }


   public delegate void f(object Src);
   public event f willStart;

   /// <summary>
   /// Start playing the video
   /// </summary>
   public void Start()
   {
      RenderPin();
      if (null != willStart)
        willStart(this);

      // We may need to force it to single CPU
      // http://social.msdn.microsoft.com/Forums/en-US/windowsdirectshowdevelopment/thread/53563921-6398-491c-999c-3bfaa2f218ca
      Process P = Process . GetCurrentProcess();
      IntPtr Mask = P . ProcessorAffinity;
      P . ProcessorAffinity = (IntPtr)(1 & (int) Mask);

      _LastError = ((IMediaControl) Graph) . Run();
      P . ProcessorAffinity = Mask;
   }

   public void Pause()
   {
      ((IMediaControl) Graph) . Pause();
   }

   /// <summary>
   /// Stop playing the video
   /// </summary>
   public void Stop()
   {
      ((IMediaControl) Graph) . StopWhenReady();
   }

const int WS_CHILD = 0x40000000;
const int WS_CLIPCHILDREN = 0x02000000;
const int WS_CLIPSIBLINGS = 0x04000000;

   public void RenderOnto(Control X)
   {
      RenderPin();
      IVideoWindow Video = (IVideoWindow) Graph;
      Video . put_Owner(X . Handle);
      Video . put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
      PreviewResize(X);
   }


   /// <summary>
   /// 
   /// </summary>
   /// <param name="X"></param>
   public void PreviewResize(Control X)
   {
      IVideoWindow Video = (IVideoWindow) Graph;
      int X0 = X.ClientRectangle.Left;
      int Y0 = X.ClientRectangle.Top;
      int Width = X.ClientRectangle.Right-X0;
      int Height= X.ClientRectangle.Bottom-Y0;
      int H1 = Width * 240 / 320;
      if (H1 < Height)
        Height = H1;
      int W1 = Height * 320 / 240;
      if (W1 < Width)
        Width = W1;
      Video . SetWindowPosition(X0,    Y0,
                                X0+Width, Y0+Height);
   }

   /// <summary>
   /// Internal tracking of the last error code
   /// </summary>
   int _LastError;

   /// <summary>
   /// Controls whether the graph pops up a window showing the stuff
   /// </summary>
   internal bool AutoShow
   {
      get
      {
         int Ret = 0;
         _LastError = ((IVideoWindow) Graph) . get_AutoShow(out Ret);
         return Ret != 0;
      }
      set{_LastError = ((IVideoWindow) Graph) . put_AutoShow(value?1:0);}
   }
}
